package com.san.paypal.controller;

import javax.servlet.http.HttpServletRequest;

import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.san.paypal.config.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.san.paypal.config.PaypalPaymentIntent;
import com.san.paypal.config.PaypalPaymentMethod;
import com.san.paypal.service.PaypalService;
import com.san.paypal.utils.URLUtil;
import com.paypal.base.rest.PayPalRESTException;

/**
 * 主要流程 1.注册paypal商户账号
 * 2.登录开发者平台或者创建开发者账号 https://developer.paypal.com”
 * 3.创建应用,可获取必要参数,clientId和clientSecret
 * 4.沙盒中创建消费账户和商家账户(别用默认的,可能会比较慢,重新添加选中国的)
 * 5.启动本项目,访问localhost:8088,点击paypal,登录沙盒中的消费账户付款,支付或取消跳转对应重定向地址
 * 6.用沙盒中账户登录https://www.sandbox.paypal.com/c2/signin查看消费记录
 * 7.退款参考main方法
 *
 * 本项目中Client中参数为我自己沙盒中的参数,可以直接用,但是后期可能我回删除,最好自己申请
 *
 *
 *  沙盒中商户号  sb-gqccf1625086@business.example.com  密码D/h5z]p*
 *  消费号:sb-qyiyd6226812@personal.example.com 密码 3+Bxe/<8
 *注:本项目参照paypal开发者网站中的api模块中sdk快速开发以及https://blog.csdn.net/qq_34579313/article/details/84848122
 *
* @author zsl
* Description:
*/
@Controller
@RequestMapping("/")
public class PaymentController {

    public static final String PAYPAL_SUCCESS_URL = "pay/success";
    public static final String PAYPAL_CANCEL_URL = "pay/cancel";

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private PaypalService paypalService;

    /**
     * 跳入支付按钮页
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    /**
     * 发起支付请求
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "pay")
    public String pay(HttpServletRequest request) {
        String cancelUrl = URLUtil.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;//请求支付传入的参数（取消支付回调地址）  发现可以乱填，待研究
        String successUrl = URLUtil.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;//请求支付传入的参数（支付成功回调地址）  发现可以乱填，待研究
        try {
        	// payment发起请求的请求数据对象,total为请求支付总金额，currency货币类型（USD为美元），description为订单描述
            Payment payment = paypalService.createPayment(
                    500.00,
                    "USD",
                    PaypalPaymentMethod.paypal,
                    PaypalPaymentIntent.sale,
                    "payment description",
                    cancelUrl,
                    successUrl);
            System.out.println("createPayment=" + payment);
            for(Links links : payment.getLinks()){
                if(links.getRel().equalsIgnoreCase("approval_url")) {
                    return "redirect:" + links.getHref();
                }
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            System.out.println(e.getDetails());
        }
        return "redirect:/";
    }

    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
    public String cancelPay() {
        return "cancel";
    }

    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
    public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) {//继续支付请求方法,paymentId,payerId这两个参数是请求支付方法成功回调自动传入
        try {
        	System.out.println("paymentId=" + paymentId + ",payerId=" + payerId);
            Payment payment = paypalService.executePayment(paymentId, payerId);//payment 支付返回相关信息，其中payer为买家相关信息，

            System.out.println("payment" + payment);
            if(payment.getState().equals("approved")) {
                return "test";//交易成功回调地址
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            System.out.println(e.getDetails());
        }
        return "redirect:/";
    }

    /**
     * 测试退款流程
     * 沙盒中用户可以在https://www.sandbox.paypal.com/c2/signin登录
     * @param args
     * @throws PayPalRESTException
     */
    public static void main(String[] args) throws PayPalRESTException {
        String paymentId = "PAYID-MCP4RNQ7AF11601XC7248004";
        APIContext apiContext = new APIContext(Client.clientID, Client.clientSecret, Client.mode);
        Payment payment = Payment.get(apiContext, paymentId);
        String id = payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getId();
        Sale sale = new Sale();
        sale.setId(id);

        Refund refund = new Refund();

        Amount amount = new Amount();
        amount.setCurrency("USD");
        amount.setTotal("0.11");
        refund.setAmount(amount);

        sale.refund(apiContext, refund);
    }
}
